# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:         GO_malwarepatrol
# Purpose:      GhostOSINT plug-in to search MalwarePatrol's daatabase for
#               potential malicious IPs/hostnames.
#
# Author:      Steve Micallef <steve@binarypool.com>
#
# Created:     25/07/2016
# Copyright:   (c) Steve Micallef 2016
# Licence:     GPL
# -------------------------------------------------------------------------------

from ghostosint import GhostOsintEvent, GhostOsintPlugin


class GO_malwarepatrol(GhostOsintPlugin):

    meta = {
        'name': "MalwarePatrol",
        'summary': "查询 malwarepatrol.net 数据库中是否存在该Url地址或IP地址为恶意地址.",
        'flags': ["apikey"],
        'useCases': ["Investigate", "Passive"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://www.malwarepatrol.net/",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://www.malwarepatrol.net/tech-support/",
                "https://www.malwarepatrol.net/integrations-formats-tip-siem-soar/",
                "https://www.malwarepatrol.net/community-contribution-suspicious-emails/",
                "https://www.malwarepatrol.net/non-commercial/#lists"
            ],
            'apiKeyInstructions': [
                "访问 https://www.malwarepatrol.net/free-guard-block-list/",
                "注册一个免费账户",
                "密码或收据编号将邮寄到你的电子邮箱"
            ],
            'favIcon': "https://www.malwarepatrol.net/wp-content/uploads/2020/02/rsz_12logo-150x150.png",
            'logo': "https://www.malwarepatrol.net/wp-content/uploads/2016/06/rsz_mp_logo_clear_-_small.png",
            'description': "总部设在美国和巴西，我们的历史是一个社区精神和致力于互联网安全的历史，始于2005年，当时一个团体开始使用简单的邮件列表共享恶意链接.\n"
            "十多年来，收集、分析和共享数据使我们能够开发一个由传感器、共享协议和社区贡献者组成的广泛网络. "
            "其结果就是我们庞大的独特且历史丰富的“智能”威胁数据数据库.",
        }
    }

    opts = {
        "api_key": "",
        'checkaffiliates': True,
        'checkcohosts': True,
    }

    optdescs = {
        "api_key": "Malwarepatrol.com '收据' ID，一旦注册就会提供.",
        'checkaffiliates': "检查关联企业?",
        'checkcohosts': "检查目标 IP地址 上共同托管的站点?",
    }

    results = None
    errorState = False

    def setup(self, sfc, userOpts=dict()):
        self.GhostOsint = sfc
        self.results = self.tempStorage()

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    def watchedEvents(self):
        return [
            "INTERNET_NAME",
            "AFFILIATE_INTERNET_NAME",
            "IP_ADDRESS",
            "AFFILIATE_IPADDR",
            "CO_HOSTED_SITE",
        ]

    def producedEvents(self):
        return [
            "BLACKLISTED_IPADDR",
            "BLACKLISTED_AFFILIATE_IPADDR",
            "BLACKLISTED_INTERNET_NAME",
            "BLACKLISTED_AFFILIATE_INTERNET_NAME",
            "BLACKLISTED_COHOST",
            "MALICIOUS_IPADDR",
            "MALICIOUS_AFFILIATE_IPADDR",
            "MALICIOUS_INTERNET_NAME",
            "MALICIOUS_AFFILIATE_INTERNET_NAME",
            "MALICIOUS_COHOST",
        ]

    def queryAddr(self, qaddr):
        data = dict()
        url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \
              self.opts['api_key'] + "&product=8&list=smoothwall"

        data['content'] = self.GhostOsint.cacheGet("sfmalwarepatrol", 72)
        if data['content'] is None:
            data = self.GhostOsint.fetchUrl(url, useragent=self.opts['_useragent'])
            if data['content'] is None:
                self.error("Unable to fetch " + url)
                return None
            self.GhostOsint.cachePut("sfmalwarepatrol", data['content'])

        for line in data['content'].split('\n'):
            if len(line) < 2 or line.startswith('#'):
                continue

            if line.startswith(qaddr):
                return True

        return False

    def handleEvent(self, event):
        eventName = event.eventType
        eventData = event.data

        if self.errorState:
            return

        self.debug(f"Received event, {eventName}, from {event.module}")

        if not self.opts['api_key']:
            self.error("You enabled GO_malwarepatrol but did not provide a receipt ID!")
            self.errorState = True
            return

        if eventData in self.results:
            self.debug(f"Skipping {eventData} as already searched.")
            return

        self.results[eventData] = True

        if eventName == 'IP_ADDRESS':
            malicious_type = "MALICIOUS_IPADDR"
            blacklist_type = "BLACKLISTED_IPADDR"
        elif eventName == 'AFFILIATE_IPADDR':
            if not self.opts.get('checkaffiliates', False):
                return
            malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
            blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
        elif eventName == "INTERNET_NAME":
            malicious_type = "MALICIOUS_INTERNET_NAME"
            blacklist_type = "BLACKLISTED_INTERNET_NAME"
        elif eventName == "AFFILIATE_INTERNET_NAME":
            if not self.opts.get('checkaffiliates', False):
                return
            malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
            blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
        elif eventName == "CO_HOSTED_SITE":
            if not self.opts.get('checkcohosts', False):
                return
            malicious_type = "MALICIOUS_COHOST"
            blacklist_type = "BLACKLISTED_COHOST"
        else:
            self.debug(f"Unexpected event type {eventName}, skipping")
            return

        if not self.queryAddr(eventData):
            return

        text = f"MalwarePatrol [{eventData}]"

        evt = GhostOsintEvent(malicious_type, text, self.__name__, event)
        self.notifyListeners(evt)

        evt = GhostOsintEvent(blacklist_type, text, self.__name__, event)
        self.notifyListeners(evt)

# End of GO_malwarepatrol class
